import Util from "./Util";
import PROTOCOL_CONFIG from './config/protocolConfig';

export default class KeyboardListener {
    constructor(containerId, msgHandler, isMobile) {
        this.containerId = containerId;
        this.msgHandler = msgHandler;
        this.keyEventCodeType = PROTOCOL_CONFIG.KEYEVENT_KEYCODE_TYPE;
        this.util = new Util();
        this.touchHandler = null;
        this.isMobile = isMobile;
        this.container = document.getElementById(this.containerId);
        this.container.setAttribute('tabindex', '-1')
    }

    start(touchHandler) {
        this.touchHandler = touchHandler;
        this.util.bind(this.container, 'keydown', this.onKeydown.bind(this));
        this.util.bind(this.container, 'keypress', this.onKeypress.bind(this));
    }

    onKeydown(event) {
        if(PROTOCOL_CONFIG.PC_KEY_MAP[event.keyCode]) {
            this.touchHandler.sendKeyCodeEventMsg(PROTOCOL_CONFIG.KEYEVENT_KEYCODE_TYPE.ACTION_DOWN, PROTOCOL_CONFIG.PC_KEY_MAP[event.keyCode]);
            this.touchHandler.sendKeyCodeEventMsg(PROTOCOL_CONFIG.KEYEVENT_KEYCODE_TYPE.ACTION_UP, PROTOCOL_CONFIG.PC_KEY_MAP[event.keyCode]);
        }
    }
    onKeypress(event) {
        if(PROTOCOL_CONFIG.PC_KEY_PRESS_MAP[event.keyCode]) {
            this.touchHandler.sendKeyCodeEventMsg(PROTOCOL_CONFIG.KEYEVENT_KEYCODE_TYPE.ACTION_DOWN, PROTOCOL_CONFIG.PC_KEY_PRESS_MAP[event.keyCode]);
            this.touchHandler.sendKeyCodeEventMsg(PROTOCOL_CONFIG.KEYEVENT_KEYCODE_TYPE.ACTION_UP, PROTOCOL_CONFIG.PC_KEY_PRESS_MAP[event.keyCode]);
        }
    }

    sendClipboardData(clipboardData) {
        let textType = PROTOCOL_CONFIG.KEYBOARD_INPUT_MSG_TYPE.IME_PASTE_FROM_PC_SDK;
        if(this.isMobile) {
          textType = PROTOCOL_CONFIG.KEYBOARD_INPUT_MSG_TYPE.IME_PASTE_FROM_SDK;
        }
        let msgType = 'KEYBOARD_INPUT';

        const PACKAGE_HEADER_LENGTH = 8;
        const INPUT_HEADER_LENGTH = 3;
        const msgData = this.util.encodeUTF8(clipboardData);
        const cmdBuf = new Uint8Array(PACKAGE_HEADER_LENGTH + INPUT_HEADER_LENGTH + msgData.length);
        cmdBuf[0] = 90;
        cmdBuf[1] = 90;
        cmdBuf[2] = 180 + PROTOCOL_CONFIG.MSG_TYPE[msgType];
        cmdBuf[3] = PROTOCOL_CONFIG.MSG_TYPE[msgType];
        cmdBuf[4] = (INPUT_HEADER_LENGTH + msgData.length) >> 24;
        cmdBuf[5] = (INPUT_HEADER_LENGTH + msgData.length) >> 16;
        cmdBuf[6] = (INPUT_HEADER_LENGTH + msgData.length) >> 8;
        cmdBuf[7] = (INPUT_HEADER_LENGTH + msgData.length);
        cmdBuf[8] = textType;
        cmdBuf[9] = msgData.length >> 8;
        cmdBuf[10] = msgData.length;

        cmdBuf.set(msgData, PACKAGE_HEADER_LENGTH + INPUT_HEADER_LENGTH);
        this.msgHandler(cmdBuf.buffer);
    }    
    
    destroy() {
        this.util.unbind(this.container, 'keydown');
        this.util.unbind(this.container, 'keypress');
    }
}